package com.swhysc.information.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * @program: tempo-dm
 * @description: ${description}
 * @author: Dongxp
 * @create: 2022-04-20 14:13
 **/
public class MapToBeanUtils {

    //JSONObject 的 key下划线转驼峰
    /**
     * 规范化参数
     * @param
     * @return
     */
    public static JSONObject covertObject(JSONObject object) {
        if (object == null) {
            return null;
        }
        JSONObject newObject = new JSONObject();
        Set<String> set = object.keySet();
        for (String key : set) {
            Object value = object.get(key);
            if (value instanceof JSONArray || value instanceof List) {
                //数组
                value = covertArray(object.getJSONArray(key));
            } else if (value instanceof JSONObject) {
                //对象
                value = covertObject(object.getJSONObject(key));
            }
            //这个方法自己写的改成驼峰，也可以改成大写小写
            key = covertName(key);
            newObject.put(key, value);
        }
        return newObject;
    }

    public static String covertName(String key){
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isBlank(key)){
            return "";
        }else if(!key.contains("_")){ //不包含下划线 全小写
            return key.toLowerCase();
        }
        String[] split = key.split("_");
        for (String s : split) {
            //跳过原始字符串中开头、结尾的下换线或双重下划线
            if (s.isEmpty()){
                continue;
            }
            if (sb.length() == 0){
                sb.append(s.toLowerCase());//下划线之前的 ，全部转小写
            }else {
                sb.append(s.substring(0, 1).toUpperCase());
                sb.append(s.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    public static JSONArray covertArray(JSONArray array) {
        if (array == null) {
            return null;
        }
        JSONArray newArray = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                //数组
                value = covertArray(array.getJSONArray(i));
            } else if (value instanceof JSONObject) {
                //对象
                value = covertObject(array.getJSONObject(i));
            }
            newArray.add(value);
        }
        return newArray;
    }

    public String convertJSONKeyRetrunString(String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject jsonResult = this.covertObject(jsonObject);
        return jsonResult.toJSONString();
    }
}
